import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;

/**
 * @author 35326
 * 2021/3/24 18:16
 */
public class NetTest {
	public static void main(String[] args) {
		System.out.println(Integer.toBinaryString(49152));
	}

	@Test
	public void client() throws IOException {
		InetAddress byName = InetAddress.getByName("127.0.0.100");
		Socket socket = new Socket(byName,9999);
		OutputStream outputStream = socket.getOutputStream();

		outputStream.write("我是客户端MM".getBytes());
		outputStream.close();
		socket.close();
	}

	@Test
	public void server(){
		try {
			ServerSocket serverSocket = new ServerSocket(9999);
			Socket accept = serverSocket.accept();
			InputStream inputStream = accept.getInputStream();
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

			byte[] bytes = new byte[1024];
			int len=-1;
			while((len=inputStream.read(bytes))!=-1){
				byteArrayOutputStream.write(bytes,0,len);
			}
			System.out.println(byteArrayOutputStream.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			;
		}
	}

	@Test
	public void send(){
		String message="我是UDP方式发送的导弹！";
		DatagramSocket datagramSocket = null;
		try {
			datagramSocket = new DatagramSocket();
			DatagramPacket datagramPacket = new DatagramPacket(message.getBytes(),
					0,message.getBytes().length,InetAddress.getLocalHost(),1);
			datagramSocket.send(datagramPacket);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			datagramSocket.close();
		}
	}

	@Test
	public void receive(){
		try {
			DatagramSocket datagramSocket = new DatagramSocket(1);

			byte[] bytes = new byte[1024];
			DatagramPacket datagramPacket = new DatagramPacket(bytes,0,1024);

			datagramSocket.receive(datagramPacket);
			System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
			datagramSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {

		}
	}
}
